package 双向链表_带哨兵;

import 单向链表.Test;

import java.util.Iterator;

public class DoubleLinkList implements Iterable<Integer> {

    // 节点类
    static class Node {
        Node pre; // 上一个节点指针
        Node next; // 下一个节点指针
        int value; // 值

        public Node(Node pre, Node next, int value) {
            this.pre = pre;
            this.next = next;
            this.value = value;
        }
    }


    // 哨兵
    private Node head; // 头哨兵
    private Node tail; // 尾哨兵


    public DoubleLinkList() { // 无参构造器
        head = new Node(null, null, 666);
        tail = new Node(null, null, 888);
        head.next = tail;
        tail.pre = head;
    }


    // 根据索引查找节点
    private Node findNode(int index) {
        int i = -1;
        Node p;
        for (p = head; p != tail; p = p.next, i++) {
            if (i == index) {
                return p;
            }
        }
        return null;
    }


    // 根据索引位置插入值
    public void insert(int index, int value) {
        Node pre = findNode(index - 1);
        if (pre == null) {
            System.out.println("索引异常~~");
            return;
        }
        Node next = pre.next;
        Node inserted = new Node(pre, next, value);
        pre.next = inserted;
        next.pre = inserted;
    }


    // 从头增加元素
    public void addFirst(int value) {
        insert(0, value);
    }


    // 从尾部增加元素
    public void addLast(int value) {
        Node last = tail.pre;
        Node added = new Node(last, tail, value);
        last.next = added;
        tail.pre = added;
    }






    // 根据索引删除元素
    public void remove(int index) {
        Node pre = findNode(index - 1);
        if (pre == null) {
            System.out.println("索引异常");
            return;
        }
        Node next = findNode(index + 1);
        if (next == null) {
            System.out.println("索引异常");
            return;
        }
        pre.next = next;
        next.pre = pre;
    }



    // 删除头元素
    public void removeFirst() {
        remove(0);
    }


    // 删除尾节点
    public void removeLast() {
        Node removed = tail.pre;
        if (removed == head) {
            System.out.println("索引异常");
            return;
        }
        Node pre = removed.pre;
        pre.next = tail;
        tail.pre = pre;
    }


    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            Node p = head.next;

            @Override
            public boolean hasNext() {
                return p != tail;
            }

            @Override
            public Integer next() {
                int v = p.value;
                p = p.next;
                return v;
            }
        };
    }
}
